﻿using GalaSoft.MvvmLight.Messaging;
using HRM.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace HRM.Model
{
    public class UserService : IUserService
    {
        public bool Login(string username, string password)
        {
            using (HRMEntities entities = new HRMEntities())
            {
                NguoiSuDung query;
                try
                {
                    query = entities.NguoiSuDungs.Where(x => x.TenDangNhap == username && x.MatKhau == password).FirstOrDefault();
                    if (query != null) return true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Lỗi kết nối CSDL \n" + ex.Message, "Thông báo", MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }
                return false;
            }
        }


        public NguoiSuDung GetUser(string username)
        {
            using (HRMEntities entities = new HRMEntities())
            {
                var query = entities.NguoiSuDungs.Where(x => x.TenDangNhap == username).FirstOrDefault();
                if (query != null) return query;
                else
                {
                    throw new Exception("Null User");
                }
            }
        }


        public bool UpdateGroup(int userid, int groupId)
        {
            using (HRMEntities entities = new HRMEntities())
            {
                var query = entities.NguoiSuDungs.Where(x => x.MaNhanVien == userid).FirstOrDefault();
                if (query != null)
                {
                    query.MaNhom = groupId;
                    entities.SaveChanges();
                    Messenger.Default.Send(new StatusMessage("Thay đỏi thành công", 3000, StatusType.Done));
                    return true;
                }
                return false;
            }
        }


        public List<NhanVien> GetStaffsNoAccount()
        {
            using(HRMEntities entities = new HRMEntities())
            {
                var users = entities.NguoiSuDungs.Select(x => x.MaNhanVien).ToList();
                var list = entities.NhanViens.Include("NguoiSuDung").Where(x => !users.Contains(x.MaNhanVien)).ToList();
                return list;
            }
        }
    }
}
